const http = require('http');
const fs = require('fs');
const path = require('path');

const server = http.createServer((req, res) => {
	console.log('Request URL:', req.url);

	// Handle root path
	let filePath;
	if (req.url === '/') {
		filePath = path.join(__dirname, '/iframe/calculators/battery-calculator.html');
		console.log('Root path requested, serving:', filePath);
	} else {
		filePath = path.join(__dirname, req.url);
	}

	console.log('Resolved file path:', filePath);

	fs.existsSync(filePath) ? console.log('File exists:', filePath) : console.log('File does not exist:', filePath);

	fs.readFile(filePath, (err, data) => {
		if (err) {
			console.error('Error reading file:', err.message);
			res.writeHead(404);
			res.end('Not Found: ' + err.message);
		} else {
			// Set appropriate content type based on file extension
			const ext = path.extname(filePath).toLowerCase();
			const contentType =
				{
					'.html': 'text/html',
					'.css': 'text/css',
					'.js': 'text/javascript',
					'.json': 'application/json',
				}[ext] || 'text/plain';

			res.writeHead(200, { 'Content-Type': contentType });
			res.end(data);
			console.log('Successfully served:', filePath);
		}
	});
});

server.listen(8000);
console.log('Server running at http://localhost:8000/');
console.log('Base directory:', __dirname);
